import java.io.*;
import java.nio.file.*;
import java.text.*;
import java.util.*;

public class BillingManagement {
    private static final String INCOME_FILE = "income.txt";
    private static final String EXPENSE_FILE = "expense.txt";
    private static final Scanner scanner = new Scanner(System.in);
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) {
        while (true) {
            displayMenu();
            int option = scanner.nextInt();
            scanner.nextLine();
            try {
            switch (option) {
                case 1:
                    recordIncome();
                    break;
                case 2:
                    recordExpense();
                    break;
                case 3:
                    showAllBills();
                    break;
                case 4:
                    queryBills();
                    break;
                case 0:
                    System.out.println("退出系统。");
                    return;
                default:
                    System.out.println("无效的选项，请重新输入。");
                    break;
            }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字序号！！！");
                continue;
            }
        }
    }

    private static void displayMenu() {
        System.out.println("=================================");
        System.out.println("欢迎使用个人账单管理系统");
        System.out.println("=================================");
        System.out.println("请选择操作：");
        System.out.println("1. 记录收入");
        System.out.println("2. 记录支出");
        System.out.println("3. 查看所有账单");
        System.out.println("4. 查询账单");
        System.out.println("0. 退出系统");
        System.out.print("请输入选项序号：");
    }

    private static void recordIncome() {
        System.out.println("请输入收入信息：");
        System.out.print("日期（YYYY-MM-DD）：");
        String date = scanner.nextLine();
        System.out.print("金额：");
        double amount = scanner.nextDouble();
        scanner.nextLine();
        System.out.print("类别（如工资、奖金等）：");
        String category = scanner.nextLine();
        System.out.print("备注：");
        String remark = scanner.nextLine();

        if (amount <= 0) {
            System.out.println("金额必须是正数，请重新输入。");
            return;
        }

        try {
            dateFormat.parse(date);
            saveRecord(INCOME_FILE, date, amount, category, remark);
            System.out.println("收入已成功记录！");
        } catch (ParseException e) {
            System.out.println("日期格式错误，请使用YYYY-MM-DD格式。");
        }
    }

    private static void recordExpense() {
        System.out.println("请输入支出信息：");
        System.out.print("日期（YYYY-MM-DD）：");
        String date = scanner.nextLine();
        System.out.print("金额：");
        double amount = scanner.nextDouble();
        scanner.nextLine();
        System.out.print("类别（如餐饮、交通、购物等）：");
        String category = scanner.nextLine();
        System.out.print("备注：");
        String remark = scanner.nextLine();

        if (amount <= 0) {
            System.out.println("金额必须是正数，请重新输入。");
            return;
        }

        try {
            dateFormat.parse(date);
            saveRecord(EXPENSE_FILE, date, -amount, category, remark);
            System.out.println("支出已成功记录！");
        } catch (ParseException e) {
            System.out.println("日期格式错误，请使用YYYY-MM-DD格式。");
        }
    }

    private static void saveRecord(String fileName, String date, double amount, String category, String remark) {
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(fileName), StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
            writer.write(String.format("%s,%f,%s,%s%n", date, amount, category, remark));
        } catch (IOException e) {
            System.out.println("无法写入文件：" + e.getMessage());
        }
    }
    private static void showAllBills() {
        try {
            System.out.println("收入：");
            List<String> incomeLines = Files.readAllLines(Paths.get(INCOME_FILE));
            for (String line : incomeLines) {
                System.out.println(line);
            }

            System.out.println("支出：");
            List<String> expenseLines = Files.readAllLines(Paths.get(EXPENSE_FILE));
            for (String line : expenseLines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("无法读取文件：" + e.getMessage());
        }
    }

    private static void queryBills() {
        System.out.println("请输入查询条件：");
        System.out.print("日期（YYYY-MM-DD）或日期范围（起始日期-结束日期）或类别（收入/支出类别）：");
        String query = scanner.nextLine();
        boolean isDateRange = query.contains("-");
        boolean isCategoryQuery = query.equals("收入") || query.equals("支出");

        try {
            if (isDateRange) {
                String[] dates = query.split("-");
                String startDate = dates[0];
                String endDate = dates[1];
                dateFormat.parse(startDate);
                dateFormat.parse(endDate);
                queryByDateRange(startDate, endDate);
            } else if (isCategoryQuery) {
                queryByCategory(query);
            } else {
                String date = query;
                dateFormat.parse(date);
                queryByDate(date);
            }
        } catch (ParseException e) {
            System.out.println("日期格式错误，请使用YYYY-MM-DD格式。");
        }
    }
    private static void queryByDate(String date) {
        System.out.println("收入：");
        queryByDateAndFile(INCOME_FILE, date);

        System.out.println("支出：");
        queryByDateAndFile(EXPENSE_FILE, date);
    }

    private static void queryByDateRange(String startDate, String endDate) {
        System.out.println("收入：");
        queryByDateRangeAndFile(INCOME_FILE, startDate, endDate);

        System.out.println("支出：");
        queryByDateRangeAndFile(EXPENSE_FILE, startDate, endDate);
    }

    private static void queryByCategory(String category) {
        if (category.equals("收入")) {
            System.out.println("收入：");
            queryByCategoryAndFile(INCOME_FILE, category);
        } else if (category.equals("支出")) {
            System.out.println("支出：");
            queryByCategoryAndFile(EXPENSE_FILE, category);
        }
    }

    private static void queryByDateAndFile(String fileName, String date) {
        try {
            List<String> lines = Files.readAllLines(Paths.get(fileName));
            for (String line : lines) {
                String[] parts = line.split(",");
                if (parts[0].equals(date)) {
                    System.out.println(line);
                }
            }
        } catch (IOException e) {
            System.out.println("无法读取文件：" + e.getMessage());
        }
    }

    private static void queryByDateRangeAndFile(String fileName, String startDate, String endDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            List<String> lines = Files.readAllLines(Paths.get(fileName));
            Date start = dateFormat.parse(startDate);
            Date end = dateFormat.parse(endDate);
            for (String line : lines) {
                String[] parts = line.split(",");
                String lineDateStr = parts[0];
                Date lineDate = dateFormat.parse(lineDateStr);
                if (!lineDate.before(start) && !lineDate.after(end)) {
                    System.out.println(line);
                }
            }
        } catch (ParseException e) {
            System.out.println("日期格式错误：" + e.getMessage());
        } catch (IOException e) {
            System.out.println("无法读取文件：" + e.getMessage());
        }
    }

    private static void queryByCategoryAndFile(String fileName, String category) {
        try {
            List<String> lines = Files.readAllLines(Paths.get(fileName));
            for (String line : lines) {
                String[] parts = line.split(",");
                if (parts[2].equals(category)) {
                    System.out.println(line);
                }
            }
        } catch (IOException e) {
            System.out.println("无法读取文件：" + e.getMessage());
        }
    }
}
//其他方法

